package com.px.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.px.common.config.RuoYiConfig;
import com.px.common.constant.Constants;
import com.px.common.core.domain.model.*;
import com.px.common.core.redis.RedisCache;
import com.px.common.exception.ServiceException;
import com.px.common.utils.SecurityUtils;
import com.px.common.utils.StringUtils;
import com.px.common.utils.file.FileUploadUtils;
import com.px.common.utils.file.MimeTypeUtils;
import com.px.framework.web.service.TokenService;
import com.px.system.domain.dto.FlightPwd;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.px.framework.aes.AesSecurityParameter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.px.common.annotation.Log;
import com.px.common.core.controller.BaseController;
import com.px.common.core.domain.AjaxResult;
import com.px.common.enums.BusinessType;
import com.px.system.domain.FlightUser;
import com.px.system.service.IFlightUserService;
import com.px.common.utils.poi.ExcelUtil;
import com.px.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 飞行用户信息Controller
 * 
 * @author WRJ
 * @date 2024-08
 */
@Api("飞行用户信息")
@RestController
@RequestMapping("/system/flightUser")
public class FlightUserController extends BaseController
{
    @Autowired
    private IFlightUserService flightUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询飞行用户信息列表
     */
    @ApiOperation("查询飞行用户信息列表")
    @PreAuthorize("@ss.hasPermi('system:flightUser:query')")
    @GetMapping("/list")
    @AesSecurityParameter(outEncode = true)
    public TableDataInfo list(FlightUser flightUser)
    {
        startPage();
        return getDataTable(flightUserService.selectFlightUserListMap(flightUser));
    }

    /**
     * 导出飞行用户信息列表
     */
    @ApiOperation("导出飞行用户信息列表")
    @PreAuthorize("@ss.hasPermi('system:flightUser:query')")
    @Log(title = "飞行用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @AesSecurityParameter(outEncode = false)
    public void export(HttpServletResponse response, FlightUser flightUser)
    {
        List<FlightUser> list = flightUserService.selectFlightUserList(flightUser);
        ExcelUtil<FlightUser> util = new ExcelUtil<FlightUser>(FlightUser.class);
        util.exportExcel(response, list, "飞行用户信息数据");
    }

    /**
     * 获取飞行用户信息详细信息
     */
    @ApiOperation("获取飞行用户信息详细信息")
    @PreAuthorize("@ss.hasPermi('system:flightUser:query')")
    @GetMapping(value = "/{userId}")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getInfo(@PathVariable("userId") Long userId)
    {
        return success(flightUserService.selectFlightUserByUserId(userId));
    }

    /**
     * 新增飞行用户信息
     */
    @ApiOperation("新增飞行用户信息")
    @PreAuthorize("@ss.hasPermi('system:flightUser:edit')")
    @Log(title = "飞行用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    @AesSecurityParameter(outEncode = true)
    public AjaxResult add(@RequestBody FlightUser flightUser)
    {
        return toAjax(flightUserService.insertFlightUser(flightUser));
    }

    /**
     * 修改飞行用户信息
     */
    @ApiOperation("修改飞行用户信息")
    @PreAuthorize("@ss.hasPermi('system:flightUser:edit')")
    @Log(title = "飞行用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    @AesSecurityParameter(outEncode = true)
    public AjaxResult edit(@RequestBody FlightUser flightUser)
    {
        return toAjax(flightUserService.updateFlightUser(flightUser));
    }

    /**
     * 删除飞行用户信息
     */
    @ApiOperation("删除飞行用户信息")
    @PreAuthorize("@ss.hasPermi('system:flightUser:remove')")
    @Log(title = "飞行用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        return toAjax(flightUserService.deleteFlightUserByUserIds(userIds));
    }

    @ApiOperation("注册飞行用户信息")
    @PostMapping("/register")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult register(@RequestBody RegisterFlightUser user)
    {
        String msg = flightUserService.register(user);
        return StringUtils.isEmpty(msg) ? success("注册成功") : error(msg);
    }

    /**
     * 获取飞行用户信息详细信息
     */
    @ApiOperation("获取飞行用户信息详细信息")
    @GetMapping(value = "/getInfo")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult getInfo()
    {
        return success(flightUserService.selectFlightUserByUserId(getUserId()));
    }

    /**
     * 修改飞行用户信息
     */
    @ApiOperation("修改飞行用户信息")
    @Log(title = "飞行用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/flightEdit")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult flightEdit(@RequestBody FlightUser flightUser)
    {
        return toAjax(flightUserService.updateFlightUser(flightUser));
    }

    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    @AesSecurityParameter(inDecode = false,outEncode = true)
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = getLoginUser();
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (flightUserService.updateUserAvatar(loginUser.getUserId(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }

    @PutMapping("/updatePwd")
    @AesSecurityParameter(outEncode = true)
    public AjaxResult updatePwd(@RequestBody FlightPwd flightPwd)
    {
        LoginUser loginUser = getLoginUser();
        String password = loginUser.getPassword();
        String newPassword = flightPwd.getNewPassword();
        if(0 == flightPwd.getType()){
            if (!SecurityUtils.matchesPassword(flightPwd.getOldPassword(), password))
            {
                return error("修改密码失败，旧密码错误");
            }
            if (SecurityUtils.matchesPassword(newPassword, password))
            {
                return error("新密码不能与旧密码相同");
            }
        }else if(1 == flightPwd.getType()){
            //验证码为空
            if(StringUtils.isNull(flightPwd.getCode()))
                throw new ServiceException("验证码为空!");

            //验证码失效
            if(StringUtils.isNull(redisCache.getCacheObject(flightPwd.getPhonenumber()+ Constants.RESET)))
                throw new ServiceException("验证码失效!");

            //验证码错误
            if(!flightPwd.getCode().equals(redisCache.getCacheObject(flightPwd.getPhonenumber()+Constants.RESET)))
                throw new ServiceException("验证码错误!");
        }

        if (flightUserService.resetUserPwd(getUserId(), SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }
}
